<template>
	<div class="ques-cate-dialog-container">
		<el-dialog title="导入试题" v-model="state.dialog.isShowDialog" width="70%">
			<el-form ref="quesImportDialogFormRef" :model="state.ruleForm" label-width="90px" v-loading="loading" :rules="rules">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="试题分类" prop="cateId">

							<el-tree-select v-model="state.ruleForm.cateId" :data="state.cateData" node-key="id" clearable
								check-strictly placeholder="请选择分类" :props="{ children: 'children', label: 'label' }" />

						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="导入文件" prop="quesFile">
							<div style="display: flex; flex-direction: column; width: 100%">
								<el-upload ref="uploadRef" class="upload-demo" drag accept=".xlsx,.xls,.zip"
									:auto-upload="false" :limit="1" :http-request="uploadToServer"
									:on-change="handlerFileChange" :on-exceed="handleExceed">
									<el-icon class="el-icon--upload">
										<ele-UploadFilled />
									</el-icon>
									<div class="el-upload__text">选择文件进行上传(仅支持.xlsx、.xls、.zip文件)</div>
									<template #tip>
										<div class="el-upload__tip">文件不能大于5M</div>
									</template>
								</el-upload>
								<div style="display: flex; justify-content: flex-end">
									<el-button type="primary" link @click="downTemplateFile">下载导入模板</el-button>
								</div>
							</div>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit()" size="default">确定</el-button>
				</span>
			</template>

		</el-dialog>
	</div>
</template>

<script setup>
import { nextTick, reactive, ref } from 'vue';
import { useQuesApi } from '/@/api/ques';
import { ElMessage, genFileId } from 'element-plus';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 引入api
const quesApi = useQuesApi();

// 定义变量内容
const quesImportDialogFormRef = ref();
const uploadRef = ref();
const loading = ref(false);

const state = reactive({
	dialog: {
		isShowDialog: false,
	},
	cateData: [],
	ruleForm: {
		cateId: ''
	}
});

const rules = reactive({
	cateId: [
		{ required: true, message: '请选择分类', trigger: 'change' },
	],
})

// 打开弹窗
const openDialog = () => {
	state.dialog.isShowDialog = true;
	nextTick(() => {
		uploadRef.value.clearFiles();
	});

	quesApi.cateTree().then(res => {
		state.cateData = res.data.children
	})

};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};

const handleExceed = (files) => {
	uploadRef.value.clearFiles();
	const file = files[0];
	file.uid = genFileId();
	uploadRef.value.handleStart(file);
	// uploadRef.value.submit();
};

const uploadToServer = (options) => {

	const formData = new FormData();
	formData.set('file', options.file);
	formData.set('cateId', state.ruleForm.cateId);
	loading.value = true

	quesApi.importQues(formData).then(() => {
		ElMessage.success('试题导入成功');
		emit('refresh');
		loading.value = false
		closeDialog();
	}).catch(() => {
		loading.value = false;
	})
};

const handlerFileChange = (uploadFile) => {
	if (!uploadFile.raw) {
		ElMessage.error('请选择要上传的文件!');
		uploadRef.value.clearFiles();
		return;
	}

	let size = uploadFile.size ? uploadFile.size : 0;
	if (size / 1024 / 1024 > 5) {
		ElMessage.error('导入文件大小不能超过5M!');
		uploadRef.value.clearFiles();
		return;
	}

	let suffix = uploadFile.name.substring(uploadFile.name.lastIndexOf('.'));

	if (suffix !== '.xlsx' && suffix !== '.xls' && suffix !== '.zip') {
		ElMessage.error('导入用户只支持excel文件或zip压缩文件!');
		uploadRef.value.clearFiles();
		return;
	}
};

//下载模板
const downTemplateFile = () => {
	quesApi.downQuesImportTemplateFile().then((res) => {
		const { data, headers, request } = res;

		// 此处当返回json文件时需要先对data进行JSON.stringify处理，其他类型文件不用做处理
		const blob = new Blob([data], { type: headers['content-type'] });
		const dom = document.createElement('a');
		const downUrl = window.URL.createObjectURL(blob);
		dom.href = downUrl;
		dom.download = decodeURIComponent('试题导入模板.xlsx');
		dom.style.display = 'none';
		document.body.appendChild(dom);
		dom.click();
		dom.parentNode?.removeChild(dom);
		window.URL.revokeObjectURL(request.responseURL);
		window.URL.revokeObjectURL(downUrl);

	});
};

const onCancel = () => {
	state.dialog.isShowDialog = false;
}

const onSubmit = () => {

	if (!quesImportDialogFormRef.value) return
	quesImportDialogFormRef.value.validate((valid) => {
		if (valid) {
			uploadRef.value.submit();
		}
	})



}

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped></style>
